<script setup lang="ts">
import type { PointGroupDetail } from '@/types/symmetry'
import { formatItaSymbol, formatSeitz } from '@/utils/formatters'
import { renderInline } from '@/utils/katex'
import { InformationCircleIcon, StarIcon } from '@heroicons/vue/24/solid'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

interface Props {
  group: PointGroupDetail
}

const props = defineProps<Props>()
const { t } = useI18n()

// 格式化复数值为简洁形式
// 格式化数值，保留必要的小数位
const formatNumber = (val: number) => {
  if (Math.abs(val) < 1e-10) return '0'
  if (Math.abs(val - Math.round(val)) < 1e-6) return Math.round(val).toString()
  return parseFloat(val.toFixed(4)).toString()
}

// 格式化复数值为简洁形式
const formatComplex = (val: { real: number; imag: number }) => {
  const { real, imag } = val
  const threshold = 1e-10

  // 纯实数
  if (Math.abs(imag) < threshold) {
    return formatNumber(real)
  }

  // 纯虚数
  if (Math.abs(real) < threshold) {
    const imagStr = formatNumber(imag)
    if (imagStr === '1') return 'i'
    if (imagStr === '-1') return '-i'
    return `${imagStr}i`
  }

  // 复数
  const realStr = formatNumber(real)
  const imagVal = Math.abs(imag)
  const imagStr = formatNumber(imagVal)

  const sign = imag >= 0 ? '+' : '-'
  const iPart = imagStr === '1' ? 'i' : `${imagStr}i`

  return `${realStr}${sign}${iPart}`
}

// 格式化矩阵为 LaTeX（简洁格式）
const formatMatrix = (matrix: number[][] | { real: number; imag: number }[][]) => {
  if (!matrix || matrix.length === 0) return ''

  // 检查是否为整数矩阵
  const isIntMatrix = matrix.every(row => row.every(val => typeof val === 'number' && Number.isInteger(val)))

  let rows
  if (isIntMatrix) {
    // 整数矩阵：直接显示整数
    rows = matrix.map(row => row.join(' & ')).join(' \\\\ ')
  } else {
    // 复数矩阵：使用 formatComplex
    rows = matrix.map(row => row.map(val => (typeof val === 'number' ? val.toString() : formatComplex(val as { real: number; imag: number }))).join(' & ')).join(' \\\\ ')
  }

  return `\\begin{pmatrix} ${rows} \\end{pmatrix}`
}

// 获取所有 irrep 标签
const irrepLabels = computed(() => {
  if (!props.group.operations || !props.group.operations.length) return []
  for (const op of props.group.operations) {
    if (op.irrepMatrices) {
      return Object.keys(op.irrepMatrices)
    }
  }
  return []
})
</script>

<template>
  <div class="space-y-8">
    <template v-if="group.operations.length">
      <!-- Symmetry Operations 表格 -->
      <div class="space-y-3">
        <h3 class="text-lg font-semibold">Symmetry Operations</h3>
        <div class="w-full overflow-x-auto">
          <table class="table-zebra table [&_td]:text-center [&_th]:text-center">
            <thead>
              <tr>
                <th>ID</th>
                <th>{{ t('views.pointGroupDetail.operations.seitz') }}</th>
                <th>{{ t('views.pointGroupDetail.operations.itaSymbol') }}</th>
                <th>{{ t('views.pointGroupDetail.operations.coordinateTriplet') }}</th>
                <th>Det</th>
                <th>nx</th>
                <th>ny</th>
                <th>nz</th>
                <th>[O3]</th>
                <th>[SU2]</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="op in group.operations" :key="op.id">
                <!-- ID & Generator Indicator -->
                <td class="font-mono">
                  <div class="relative inline-block">
                    {{ op.id }}
                    <StarIcon v-if="group.generators.includes(op.id)" class="text-warning absolute top-1/2 -right-4 size-3 -translate-y-1/2" />
                  </div>
                </td>

                <!-- Seitz Symbol -->
                <td v-html="renderInline(formatSeitz(op.seitz))"></td>

                <!-- ITA Symbol -->
                <td v-html="renderInline(formatItaSymbol(op.itaSymbol))"></td>

                <!-- Coordinate Triplet -->
                <td v-html="renderInline(`(${op.coordinateTriplet})`)"></td>

                <!-- Det -->
                <td class="font-mono text-sm">
                  {{ op.det !== undefined ? (op.det > 0 ? '+1' : '-1') : '-' }}
                </td>

                <!-- Axis (nx, ny, nz) -->
                <td class="font-mono text-xs">{{ op.axis?.[0]?.toFixed(2) ?? '-' }}</td>
                <td class="font-mono text-xs">{{ op.axis?.[1]?.toFixed(2) ?? '-' }}</td>
                <td class="font-mono text-xs">{{ op.axis?.[2]?.toFixed(2) ?? '-' }}</td>

                <!-- [O3] 矩阵 -->
                <td v-html="renderInline(formatMatrix(op.matrix))"></td>

                <!-- [SU2] 矩阵 -->
                <td>
                  <span v-if="op.su2" v-html="renderInline(formatMatrix(op.su2))"></span>
                  <span v-else class="text-xs opacity-50">-</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Symmetry Operations 说明 -->
        <div class="alert">
          <InformationCircleIcon class="text-info size-5 shrink-0" />
          <div class="text-sm">
            <ul class="list-inside list-disc space-y-0.5 opacity-80">
              <li v-if="group.generators.length">
                <span class="inline-flex items-center gap-1">
                  <StarIcon class="text-warning size-4" />
                  <span>{{ t('views.pointGroupDetail.operations.generatorHint') }}</span>
                </span>
              </li>
              <li>{{ t('views.pointGroupDetail.matrices.info.o3') }}</li>
              <li>{{ t('views.pointGroupDetail.matrices.info.su2') }}</li>
              <li v-if="group.crystalSystem === 'trigonal'">
                {{ t('symmetry.coordinateSystem.title') }}:
                {{ t('symmetry.coordinateSystem.note') }}
              </li>
            </ul>
          </div>
        </div>
      </div>

      <!-- Matrix Representations 表格 -->
      <div v-if="irrepLabels.length" class="space-y-3">
        <h3 class="text-lg font-semibold">Matrix Representations</h3>
        <div class="w-full overflow-x-auto">
          <table class="table-zebra table [&_td]:text-center [&_th]:text-center">
            <thead>
              <tr>
                <th>ID</th>
                <th>{{ t('views.pointGroupDetail.operations.seitz') }}</th>
                <th v-for="label in irrepLabels" :key="label">{{ label }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="op in group.operations" :key="op.id">
                <!-- ID & Generator Indicator -->
                <td class="font-mono">
                  <div class="relative inline-block">
                    {{ op.id }}
                    <StarIcon v-if="group.generators.includes(op.id)" class="text-warning absolute top-1/2 -right-4 size-3 -translate-y-1/2" />
                  </div>
                </td>

                <!-- Seitz Symbol -->
                <td v-html="renderInline(formatSeitz(op.seitz))"></td>

                <!-- Irrep 矩阵列 -->
                <td v-for="label in irrepLabels" :key="`${op.id}-${label}`">
                  <span v-if="op.irrepMatrices?.[label]" v-html="renderInline(formatMatrix(op.irrepMatrices[label]))"></span>
                  <span v-else class="text-xs opacity-50">-</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Matrix Representations 说明 -->
        <div class="alert">
          <InformationCircleIcon class="text-info size-5 shrink-0" />
          <div class="text-sm">
            <p class="opacity-80">{{ t('views.pointGroupDetail.matrices.info.irreps') }}</p>
          </div>
        </div>
      </div>
    </template>

    <!-- 空状态 -->
    <div v-else class="flex-center min-h-[200px] flex-col gap-4">
      <div class="text-4xl">📊</div>
      <p class="text-sm opacity-70">{{ t('views.pointGroupDetail.operations.noData') }}</p>
    </div>
  </div>
</template>
